<template>
  <el-dialog v-model="visible" :title="title" width="600px">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>

      <!-- 父级菜单选择框 -->
      <el-form-item label="父级菜单" prop="parent_id" v-if="isNewMode">
        <el-select v-model="formData.parent_id" :key="allMenuOptions.length">
          <el-option
            v-for="item in allMenuOptions"
            :key="item.id"
            :label="renderLabelWithIndent(item, item.level)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 编辑且为父级菜单时隐藏路径输入框 -->
      <el-form-item label="接口地址" prop="path" v-if="!isParentMenu">
        <el-input v-model="formData.path" :disabled="isParentMenu" />
      </el-form-item>

      <el-form-item v-if="formData.parent_id !== 0" label="前端组件" prop="component">
        <el-input v-model="formData.component" />
      </el-form-item>

      <el-form-item label="图标" prop="icon">
        <el-popover placement="bottom-start" width="360" trigger="click" v-model:visible="iconDialogVisible">
          <template #reference>
            <el-input v-model="formData.icon" placeholder="请选择图标" readonly style="width: 180px; cursor: pointer;">
              <template #suffix>
                <span v-if="formData.icon" class="icon-box">
                  <component :is="$icons[formData.icon]" class="icon-inner" />
                </span>
              </template>
            </el-input>
          </template>
          <el-input v-model="iconSearch" placeholder="搜索图标" clearable style="margin-bottom: 12px;" />
          <div class="icon-grid-scroll">
            <div
              v-for="item in filteredIconOptions"
              :key="item.value"
              class="icon-cell"
              :class="{ active: formData.icon === item.value }"
              @click="selectIcon(item.value)"
            >
              <span class="icon-box">
                <component :is="$icons[item.value]" class="icon-inner" />
              </span>
              <div class="icon-label">{{ item.label }}</div>
            </div>
          </div>
        </el-popover>
      </el-form-item>

      <el-form-item label="排序" prop="order_num">
        <el-input-number v-model="formData.order_num" />
      </el-form-item>
      <el-form-item label="是否隐藏" prop="hidden">
        <el-switch v-model="formData.hidden" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="是否缓存" prop="keep_alive">
        <el-switch v-model="formData.keep_alive" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item v-if="formData.parent_id !== 0" label="重定向" prop="redirect">
        <el-input v-model="formData.redirect" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { funPick } from '@/utils/common'
import { useMenuStore } from '@/stores/menuStore'

const menuStore = useMenuStore()

// 递归渲染带缩进的菜单标签
const renderLabelWithIndent = (menu, level = 0) => {
  const indent = '---'.repeat(level)
  return `${indent}${menu.name}`
}

// 使用 store 中带层级信息的菜单列表
const allMenuOptions = computed(() => menuStore.flatMenuListWithLevel)


// ====================
// Props 定义与 Emits
// ====================
const props = defineProps({
  modelValue: Boolean,
  formData: Object
})

const emit = defineEmits(['update:modelValue', 'submit'])


// ====================
// 响应式数据与 Props/Emits
// ====================
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const title = computed(() => (formData.value.id ? '编辑菜单' : '新增菜单'))

const formRef = ref(null)
const formData = ref({
  name: '',
  path: '',
  component: '',
  icon: '',
  order_num: 0,
  parent_id: 0,
  hidden: 0,
  keep_alive: 1,
  redirect: ''
})

// ====================
// 表单初始化逻辑
// ====================
// 初始化表单数据
watch(
  () => props.formData,
  (val) => {
    formData.value = val
      ? funPick(val, ['id', 'name', 'path', 'component', 'icon', 'order_num', 'hidden', 'keep_alive', 'redirect', 'parent_id'])
      : {
          name: '',
          path: '',
          component: '',
          icon: '',
          order_num: 0,
          parent_id: 0,
          hidden: 0,
          keep_alive: 1,
          redirect: ''
        }
  },
  { immediate: true }
)

// ====================
// 新增/编辑状态判断
// ====================
const isNewMode = computed(() => !formData.value.id)
const isParentMenu = computed(() => formData.value.parent_id === 0)

// ====================
// 图标选择逻辑
// ====================
const { appContext } = getCurrentInstance()
const $icons = appContext.config.globalProperties.$icons

const allIconOptions = Object.keys($icons).map(key => ({
  label: key,
  value: key
}))

const iconDialogVisible = ref(false)
const iconSearch = ref('')
const filteredIconOptions = computed(() =>
  allIconOptions.filter((item) =>
    item.label.toLowerCase().includes(iconSearch.value.toLowerCase())
  )
)

function selectIcon(val) {
  formData.value.icon = val
  iconDialogVisible.value = false
}

// ====================
// 表单验证与提交
// ====================
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  order_num: [{ type: 'number', message: '排序必须为数字', trigger: 'blur' }]
}

// 表单提交触发方法
const handleSubmit = async () => {
  try {
    await formRef.value.validate() // 恢复表单验证
    emit('submit', formData.value) // 通知父组件处理提交逻辑
    visible.value = false   // 关闭弹窗
  } catch (error) {
    ElMessage.error('请填写完整的表单信息')
  }
}
</script>

<style scoped>
.icon-grid-scroll {
  display: grid;
  grid-template-columns: repeat(4, 72px);
  gap: 12px;
  max-height: 320px;
  overflow-y: auto;
  padding-right: 8px;
}
.icon-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 6px;
  padding: 4px;
  transition: border-color 0.2s;
}
.icon-cell.active {
  border-color: var(--primary-color);
  background: #f0f7ff;
}
.icon-label {
  font-size: 10px;
  margin-top: 2px;
  color: #666;
}
.icon-box {
  width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background: #f4f4f4;
  margin-right: 4px;
}
.icon-inner {
  font-size: 16px;
  display: block;
}
</style>